<template>
  <customDrawer
    :title="pdfview.title"
    :hideConfirm="true"
    placement="top" :footer="null"
    :widthPx="300"
    :heightPx="291"
    @hide="hide"
    ref="customDrawerPdfView">
    <template #content>
      <customSpace fullWidth style="margin: 5px 0px;">
        <template #content>
          <customButton  title="打印" theme="primary" size="medium" @click="print" :disabled="isPdfBuildError || !isLodopOk"/>
          <customButton  title="关闭" theme="default" size="medium" @click="$refs.customDrawerPdfView.hide()"/>
        </template>
      </customSpace>
      <div id="box-form" class="box-title" style="margin: 10px 0px">打印设置</div>
      <customForm :data="pdfview"  ref="printForm" layoutMini :rules="rules" >
        <template #content>
          <customFormItem label="服务地址" name="printerServerUrl" :parent="_self" :form="pdfview"
                          fullWidth
                          @change="printerServerUrlChange"
                          appendBtn
                          disabled
          >
            <template #appendBtn>
              <customButton  title="更换" theme="primary" size="small" @click="changeServerUrl" />
            </template>
          </customFormItem>
          <customFormItem
            label=""
            name="msg"
            :parent="_self"
            :form="pdfview"
            :type="constCommon.formItemType.slot.name"
            fullWidth

          >
            <template #content>
              <div style="padding-left: 60px;font-size: 11px">服务地址与手机所在网络可以互通</div>
            </template>
          </customFormItem>
          <customFormItem label="打印机" name="printerName" :parent="_self" :form="pdfview"
                          :type="constCommon.formItemType.selectStatic.name"
                          :config="{options: printers, label: 'name', value: 'name'}" fullWidth
                          ref="printerName"
          />

          <customFormItem label="纸张方向" name="direction" :parent="_self" :form="pdfview"
                          :type="constCommon.formItemType.selectStatic.name"
                          :config="{options: [{label:'横向',value: 'transverse'},{label:'纵向',value: 'longitudinal'}]}"
                          full-width
          />

          <!--
                    <customFormItem label="纸张大小" name="pageSize" :parent="_self" :form="pdfview"
                                    :type="constCommon.formItemType.selectStatic.name"
                                    :config="{options: [{label:'A4(标准打印机)',value: 'A4'},{label:'A5(针式打印机)',value: 'A5'}]}"
                                    full-width
                    />
                    <customFormItem label="间距模式" name="spacingMode" :parent="_self" :form="pdfview"
                                    :type="constCommon.formItemType.selectStatic.name"
                                    :config="{options: [{label:'正常间距',value: 'normal'},{label:'无间距',value: 'no_spacing'}]}"
                                    full-width
                    />
                    <customFormItem label="纸张方向" name="direction" :parent="_self" :form="pdfview"
                                    :type="constCommon.formItemType.selectStatic.name"
                                    :config="{options: [{label:'横向',value: 'transverse'},{label:'纵向',value: 'longitudinal'}]}"
                                    full-width
                    />

                    <customFormItem label="每页数量" name="perRowsOfGrid" :parent="_self" :form="pdfview"
                                    :type="constCommon.formItemType.inputNumber.name"
                                    full-width
                    />-->
        </template>
      </customForm>
      <div id="box-show" class="box-title" style="margin: 10px 0px">打印预览</div>
      <div class="pdfview-box"  id="pdfviewBox" >
        <vueshowpdf
          v-model="isShowPdf"
          ref="pdfviewRef"
          :pdfurl="cpPdfviewSrc"
          class="pdfview-custom"
          @pdferr="pdferr"
          :scale="2"
        />
      </div>
    </template>
  </customDrawer>
</template>

<script>
import utilPrint from '@/util/utilPrint.js'
import LodopModel from '@/util/lodop/LodopModel.js'
import vueshowpdf from 'vueshowpdf'


export default {
  desc: '表单打印',
  name: 'printForm',
  components: { vueshowpdf  },
  props: {
  },
  mounted() {
    this.getStoreUserForm()
  },
  data() {
    return {
      pdfview: {
        title: 'pdf预览',
        src: null,
        pageSize: 'A4',
        direction: 'transverse',
        spacingMode: 'normal',
        perRowsOfGrid: 20,
        printerServerUrl: 'localhost',
        printerName: '',
      },

      printers: [],
      userLodopModel: null,
      isShowPdf: false,
      isImsgLoad: false,
      isShow: false,
      isLodopOk: false,
      isPdfBuildError: false,
      rules: {
        printerServerUrl: [{ required: true, message: '请输入', trigger: 'blur' }],
        printerName: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
    }
  },
  methods: {
    show(param) {
      this.isShow = true
      if (this.strings.isNotBlank(this.pdfview.printerServerUrl) && this.userLodopModel == null) {
        this.printerServerUrlChange()
      }
      this.isImsgLoad = false
      this.isPdfBuildError = false
      Object.keys(param).forEach(key => {
        if (this.strings.isNotBlank(param[key])) {
          this.$set(this.pdfview, key , param[key])
        }
      })
      console.log('cpPdfviewSrc', this.cpPdfviewSrc)
      this.$refs.customDrawerPdfView.show()
      this.isShowPdf = true
    },
    hide() {
      this.isShow = false
      this.$emit('hide')
    },
    // 初始化图片
    print() {
      //设置打印机属性
      this.userLodopModel.printerName = this.pdfview.printerName
      this.userLodopModel.printerPage = this.pdfview.pageSize
      this.userLodopModel.setPrinter()
      this.userLodopModel.lodop.SET_PRINT_MODE("CATCH_PRINT_STATUS",true)
      let that = this
      this.userLodopModel.lodop.On_Return=function(TaskID,Value){
        setTimeout(() => {
          that.utilMessage.success('打印任务已提交')
        }, 1000)
      }
      let style= ``
      let direction = 1

      let theCanvas = $('#pdfviewBox').find('#the-canvas')
      let tempSrc = theCanvas[0].toDataURL("image/png")

      // 横向
      if (this.pdfview.direction == 'transverse') {
        style= ` style="transform: rotate(90deg)"`
        //1 纵向打印，固定纸张 2 横向打印，固定纸张  http://www.c-lodop.com/demolist/PrintSample5.html
        // that.userLodopModel.lodop.SET_PRINT_PAGESIZE(2,0,utilPrint.paperSizeMap.A4.width,utilPrint.paperSizeMap.A4.height);
        // that.userLodopModel.lodop.SET_PRINT_PAGESIZE(2,0,utilPrint.paperSizeMap.A4.width,utilPrint.paperSizeMap.A4.height);
        // that.userLodopModel.lodop.ADD_PRINT_IMAGE(0,0,"98%","98%",`<img border='0' style="width: 100%;transform: rotate(90deg)" src='${tempSrc}' />`)
        // that.userLodopModel.lodop.ADD_PRINT_IMAGE(0,0,"98%","98%",`<img border='0' style="width: 100%;" src='${tempSrc}' />`)
        that.userLodopModel.lodop.SET_PRINT_PAGESIZE(2,0,utilPrint.paperSizeMap.A4.width,utilPrint.paperSizeMap.A4.height);
      } else{
        //intOrient,intPageWidth,intPageHeight,strPageName
        //1 纵向打印，固定纸张 2 横向打印，固定纸张  http://www.c-lodop.com/demolist/PrintSample5.html
        // that.userLodopModel.lodop.SET_PRINT_PAGESIZE(1,0,utilPrint.paperSizeMap.A4.height,utilPrint.paperSizeMap.A4.height);
        // that.userLodopModel.lodop.ADD_PRINT_IMAGE(0,0,"98%","98%",`<img border='0' style="width: 100%;" src='${tempSrc}' />`)

        that.userLodopModel.lodop.SET_PRINT_PAGESIZE(1,0,utilPrint.paperSizeMap.A4.width,utilPrint.paperSizeMap.A4.height);
      }
      that.userLodopModel.lodop.ADD_PRINT_PDF(0,0,"100%","100%",this.cpPdfviewSrc);


      // that.userLodopModel.lodop.ADD_PRINT_IMAGE(0,0,"98%","98%",`<img border='0' style="width: 100%;" src='${tempSrc}' />`)
      this.userLodopModel.lodop.PRINT()
    },

    //初始化打印设置
    initPrintSuccess() {
      this.isLodopOk = true
      var param={
        checkUsable:true
      }
      this.userLodopModel = new window.LodopModel(param);
      //打印机列表
      this.printers = this.userLodopModel.getPrinters()
    },

    loadImg() {
      this.isImsgLoad = true
    },

    // 保存配置
    setStoreUserForm() {
      localStorage.setItem('print_form_app',JSON.stringify(this.pdfview))
    },

    getStoreUserForm() {
      let param = localStorage.getItem('print_form_app')
      if (param) {
        let paramOb = JSON.parse(param)
        Object.keys(paramOb).forEach(key => {
          if (this.strings.isNotBlank(paramOb[key])) {
            this.$set(this.pdfview, key , paramOb[key])
          }
        })
      }
    },

    //服务地址变化
    changeServerUrl() {
      let that = this
      this.utilMessage.confirmInput('请输入地址,如:192.168.0.1', (value) => {
        value = that.strings.trim(value)
        if (value != 'localhost') {
          const re = /^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[0-9])\.((1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.){2}(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$/
          if (!re.test(value)) {
            that.utilMessage.warning('请输入合法地址')
            return
          }
        }

        that.utilMessage.confirmInputHide()
        that.$set(that.pdfview,'printerServerUrl', value)
        that.printerServerUrlChange()
      },'地址',false)
    },

    //服务地址变化
    printerServerUrlChange() {
      this.userLodopModel = null
      this.isLodopOk = false
      utilPrint.isNeedCLodopfuncs(this.pdfview.printerServerUrl,() => {this.initPrintSuccess()})
    },

    // pdf渲染失败
    pdferr(e) {
      console.log('pdferr', e)
      this.utilMessage.error('pdf生成失败，请稍候重试')
      this.isPdfBuildError = true
    }
  },
  watch: {
    // 监听变化
    pdfview: {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler(newValue, oldValue) {
        if (newValue && this.isShow) {
          this.setStoreUserForm()
        }
      },
    },
  },
  computed: {
    // pdf预览地址
    cpPdfviewSrc() {
      let pdfSrc = this.pdfview.src
      if (!pdfSrc) {
        return  null
      }
      pdfSrc= `${location.origin}/api${pdfSrc}`
      if (pdfSrc.indexOf("?") != -1) {
        pdfSrc += '&tms='+Date.now()
      } else {
        pdfSrc += '?tms='+Date.now()
      }
      pdfSrc += `&X-Token=${sessionStorage.getItem('X-Token')}`
      pdfSrc += "&pageSize="+this.pdfview.pageSize+"&direction="+this.pdfview.direction+"&spacingMode="+this.pdfview.spacingMode+"&perRowsOfGrid="+this.pdfview.perRowsOfGrid

      return pdfSrc
    }
  },
}
</script>

<style lang="scss" scoped>
.pdfview-box{
  width: 100%;
  overflow: auto;
  height: 200px;
  /* display: none;*/
  .pdfview-custom{
    position: relative !important;
    /deep/ .contor{
      display: none;
    }
  }
}

.printBox-root{
  width: 100vw;
  max-width: calc(100vw - 20px);
  overflow: auto;
  height: 100vw;
}

</style>
